import Vue from "vue";
import Vuex from "vuex";
import createPersistedState from 'vuex-persistedstate';
import axios from 'axios'

Vue.use(Vuex);




const state = {
  user: {
    id: '',
    name: "",
    password: null,
    phone: "",
    status: 0,
    cardCase: '',
    time: "",
    handUrl: "",
    gender: "",
  },
  isLogin: false,
  isAdmin: false,
  baseUrl: "/api/",
};

const mutations = {
  setUser(state, user) {
    
 
    if(user && user.handUrl) {
      user.handUrl =  "/api/" + user.handUrl;
    }
    state.user = user;
    state.isLogin = !!user 
    localStorage.setItem("isLogin",!!user )
   
    
  },
  setIsAdmin(state, isAdmin) {
    state.isAdmin = isAdmin;
    
  },
  setIsLogin(state, isLogin) {
    state.isLogin = isLogin;
    
  },


};


const actions = {
  async login({ commit }, { url, body }) {
  
    const {data:res} = await axios.post('/api'+ url, body);
    if(res.code == 200) {
      commit("setUser", res.data);
   
      commit("setIsAdmin", !!res.data.privileges);
     
      
    } 
    return res ;
  },

  

  async UserUpdate({ commit }, info) {
    const {data:res} = await axios.put('/api/user' , info)
    if(res.code == 200){
        commit("setUser", res.data);
    } 
  },
};
const getters = {
  user: (state) => state.user,
  isLogin: (state) => state.isLogin,
  isAdmin: (state) => state.isAdmin,
  baseUrl: (state) => state.baseUrl,
};

export default new Vuex.Store({
  state,
  mutations,
  actions,
  getters,
  plugins: [
    createPersistedState({
      storage: window.sessionStorage,
      key: "store",
      reducer(state) {
        return { ...state };
      }
    })
  ]

});
